
import Icon from './index';
import { dom } from '../../tool';

export interface IconMap {
    key: string;
    icon: string;
    disabled?: boolean;
}

interface PropsType {
    iconList: IconMap[];
    value?: string | null;
    onChange?: (value: string | null | undefined) => void;
    target?: HTMLElement;
    label?: string | HTMLElement;
}

interface IconSelectType {
    new(props?: PropsType): IconSelectType;
    value?: string | null;
    setValue: (value?: string | null) => void;
    onChange?: (value: string | null | undefined) => void;
    render: (node?: HTMLElement) => void;
}

function IconSelect(this: IconSelectType, props?: PropsType) {
    const { target, value: defaultValue = 'left', onChange, iconList = [] } = props || {};
    this.onChange = onChange;
    this.value = defaultValue;
    const container = dom('div', {
        target,
        style: 'display: flex; justify-content: space-around;padding: 4px 0;'
    })
    let change: any = null;
    const iconInstances = iconList.map((item: IconMap, index: number) => new Icon({
        type: item.icon,
        target: container,
        onClick: () => {
            change(item.key, !iconInstances[index].active);
        }
    }));
    change = (type: string, arg: boolean, hasChange?: boolean) => {
        iconInstances.forEach((item: any) => item.setActive(false));
        if (type) {
            let n = -1;
            for (let i = 0; i < iconList.length; i++) {
                if (type == iconList[i].key) {
                    n = i;
                    break;
                }
            }
            if (n > -1) {
                this.value = arg ? type : null;
                iconInstances[n].setActive(arg);
            } else {
                this.value = null;
            }
        } else {
            this.value = null;
        }
        if (this.onChange instanceof Function && !hasChange) {
            this.onChange(this.value);
        }
    }

    this.setValue = (arg: string | null | undefined) => {
        change(arg, true, true);
    }
    this.setValue(defaultValue);

    this.render = (node) => {
        if (node instanceof Node) {
            node.appendChild(container);
        }
        return container;
    }
    return this;
}

export default IconSelect as unknown as IconSelectType;